package com.tianheng.modbus.nettyservice;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/7/6 0006
 * since:      1.0.0.1
 * description:
 *
 **************************************************/
public class Server {

    private int port;
    public static Map<String, Channel> map = new ConcurrentHashMap<String, Channel>();
    public static Map<String, String> macMap = new HashMap<String, String>();

    public Server(int port){
        this.port=port;
    }

    public void start() throws Exception{

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        workerGroup.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("xx");
            }
        },10, TimeUnit.SECONDS);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
                    handler(new LoggingHandler(LogLevel.INFO)).
                    childHandler(new ServerChannelInitializer()).
                    option(ChannelOption.SO_BACKLOG, 1024).
                    childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            if(channelFuture.isSuccess()){
                System.out.println("服务启动已成功!");
            }
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
}
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static Map<String, Channel> getMap() {
        return map;
    }

    public static void setMap(Map<String, Channel> map) {
        Server.map = map;
    }

    public static Map<String, String> getMacMap() {
        return macMap;
    }

    public static void setMacMap(Map<String, String> macMap) {
        Server.macMap = macMap;
    }
}
